<?php

class AuctionLimitDao extends CFormModel
{

    const AUCTION_LIMIT = 'AUCTION';

    const AUTO_BID_LIMIT = 'AUTO_BID';

    public $auctionId;

    public $customerId;

    public function init()
    {}

    public function primaryKey($type)
    {
        $primaryKey = $this->auctionId . ':' . $type;
        if ($type == self::AUTO_BID_LIMIT) {
            $primaryKey .= ':' . $this->customerId;
        }
        return $primaryKey;
    }

    public function add($endTime, $type = self::AUCTION_LIMIT)
    {
        $limitSQL = '
            INSERT INTO 
                auction_limit 
            VALUES (
                "' . $this->primaryKey($type) . '",
                "' . $this->auctionId . '",
                "' . $this->customerId . '",
                "' . time() . '",
                "' . $endTime . '",
                "' . $type . '"
            ) 
            ON DUPLICATE KEY UPDATE
                auction_limit.winner_id = ' . $this->customerId . ',
                auction_limit.winner_time = ' . time() . ',
                auction_limit.end_time = ' . $endTime . '
        ';
        return Yii::app()->db->createCommand($limitSQL)->execute();
    }

    public function deleteLimit($type="AUCTION"){
        $delSql = '
     			DELETE FROM  auction_limit 
           		WHERE
                	auction_limit.winner_id = ' . $this->customerId . '
           		AND
                    auction_limit.end_time >= ' . time() . '
                AND
                    auction_limit.auction_id='.$this->auctionId.'
                AND
                     auction_limit.limit_type="'.$type.'"
     			';
        return Yii::app()->db->createCommand($delSql)->execute();
    }
    
    public function del($type)
    {
        $delSql = '
     			DELETE FROM  auction_limit 
           		WHERE
                	auction_limit.winner_id = ' . $this->customerId . '
           		AND
                auction_limit.end_time >= ' . $this->auctionId . ' 
     			';
        return Yii::app()->db->createCommand($delSql)->execute();
    }
    
    public function getLimitNum($search=array()){
        if (!array_key_exists('end_time', $search)) {
            $search['time'] = time();
        }
        if (!array_key_exists('type', $search)){
            $search['type']="AUTO_BID";
        }
        $limitNumberSQL = '
           SELECT
                COUNT(distinct auction_limit.auction_id) as number
           FROM
                auction_limit
           WHERE
                auction_limit.winner_id = ' . $this->customerId . '
           AND
                auction_limit.end_time >= ' . $search['time'] . '
           AND
                auction_limit.limit_type="'.$search["type"].'"
       ';
        if (array_key_exists('auction', $search)) {
            $limitNumberSQL .= ' AND auction_limit.auction_id = "' . $search['auction'] . '"';
        }
        $limitNumber = Yii::app()->db->createCommand($limitNumberSQL)->queryRow();
        return $limitNumber['number'];
    }
    
    //get limitNum from orders
    public function getLimitOfOrders($search=array()){
        if (!array_key_exists('end_time', $search)) {
            $search['time'] = time()-Yii::app()->params['auctionLimitExpiredTime'];
        }
        $limitNumberSql='
                                           SELECT
                                                COUNT(distinct orders.auction_id) as number
                                           FROM
                                                orders
                                           WHERE
                                                orders.customer_id = ' . $this->customerId . '
                                           AND
                                                orders.created >= ' . $search['time'] . ' 
                                           AND
                                                orders.type=1
                                    ';
        $limitNumber = Yii::app()->db->createCommand($limitNumberSql)->queryRow();
        return $limitNumber['number'];
    }
    
    /*
     *  get all limit number from auction_limit,orders 
    */
    public function limit($search = array())
    {
        if (! array_key_exists('end_time', $search)) {
            $search['time'] = time();
        }
        if(!array_key_exists('excludeTypes', $search) || !is_array($search['excludeTypes'])){
        	$search['excludeTypes']=array('AUTO_BID','BUY_IT_NOW');
        }
        $limitNumberSQL = '
           SELECT
                COUNT(distinct auction_limit.auction_id) as number
           FROM
                auction_limit
           WHERE
                auction_limit.winner_id = ' . $this->customerId . '
           AND
                auction_limit.end_time >= ' . $search['time'] . ' 
       ';
        if (array_key_exists('type', $search) && in_array($search['type'], $search['excludeTypes'])){
        	$search['excludeTypes']=array();
        }
        if (array_key_exists('type', $search)) {
            $limitNumberSQL .= ' AND auction_limit.limit_type = "' . $search['type'] . '"';
        }
        if (array_key_exists('auction', $search)) {
            $limitNumberSQL .= ' AND auction_limit.auction_id = "' . $search['auction'] . '"';
        }
        if (!empty($search['excludeTypes'])){
        	foreach ($search['excludeTypes'] as &$exclude){
     			$exclude='"'.$exclude.'"';
     		}
        	$limitNumberSQL.=' AND auction_limit.limit_type NOT IN ('.implode(',', $search['excludeTypes']).')';
        }
        
        $log=new SiteLogs();
        $log->attributes=[
            "type"=>"AuctionLimit limit  sql",
            "msg"=>json_encode(array_merge($this->attributes,[
                "sql"=>$limitNumberSQL
            ])),
            "created"=>time()
        ];
        $log->save();
        
        $limitNumber = Yii::app()->db->createCommand($limitNumberSQL)->queryRow();
        $endLimitNumber=0;
        /* if (!array_key_exists('type', $search)){
            $endLimitNumber=$this->getLimitOfOrders();
        } */
        return 0;
        return $limitNumber['number']+$endLimitNumber;
    }

    public function valid()
    {
        Yii::app()->db->createCommand($bidSQL)->execute();
    }
}